# -*- coding: utf-8 -*-
# @Time    : 2019/10/20 19:40
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : my_orm.py
# 需求,模拟django orm
import numbers


class Field(object):
    """字段类，用于判断属性是否为该类型还是属性为魔法方法"""
    pass


class IntField(Field):
    # 属性描述符
    def __init__(self, db_column=None, min_value=None, max_value=None):
        self._value = None
        self.min_value = min_value
        self.max_value = max_value
        self.db_column = db_column
        if min_value is not None:
            """参数检查"""
            if not isinstance(min_value, numbers.Integral):
                raise ValueError("min_value must be int")
            elif min_value < 0:
                raise ValueError("min_value must be positive int")
        if max_value is not None:
            if not isinstance(max_value, numbers.Integral):
                raise ValueError("min_value must be int")
            elif max_value < 0:
                raise ValueError("min_value must be positive int")
        if max_value is not None and min_value is not None:
            if min_value > max_value:
                raise ValueError("min_value must be smaller than max_value")

    def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        if not isinstance(value, numbers.Integral):
            raise ValueError("int value need")
        if value < self.min_value or value > self.max_value:
            raise ValueError("value must between min_value and max_value")
        self._value = value


class CharField(Field):
    def __init__(self, db_column=None, max_length=None):
        self._value = None
        self.db_column = db_column
        if max_length is None:
            raise ValueError("you must specify max_length for charfield")
        self.max_length = max_length

    def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise ValueError("str value need")
        if len(value) > self.max_length:
            raise ValueError("value len excess len of max_length")
        self._value = value


class ModelMetaClass(type):
    """元类，控制类实例化过程，对实例添加额外信息，如提取类的变量"""
    def __new__(cls, name, bases, attrs, **kwargs):
        if name == "BaseModel":
            return super(ModelMetaClass, cls).__new__(cls, name, bases, attrs, **kwargs)
        fields = {}
        for key, value in attrs.items():
            if isinstance(value, Field):
                fields[key] = value  # 记录了所有数据表相关的列
        attrs_meta = attrs.get("Meta", None)  # 获取元信息
        _meta = {}
        db_table = name.lower()  # 默认表名为类名小写
        if attrs_meta is not None:
            table = getattr(attrs_meta, "db_table", None)  # 元信息中定义了db_table，覆盖原表名
            if table is not None:
                db_table = table
        _meta["db_table"] = db_table
        attrs["_meta"] = _meta   # 拼装字段
        attrs["fields"] = fields
        del attrs["Meta"]
        return super().__new__(cls, name, bases, attrs, **kwargs)


class BaseModel(metaclass=ModelMetaClass):
    def __init__(self, *args, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)  # 使用属性描述符对属性赋值
        return super().__init__()
    
    def save(self):
        fields = []
        values = []
        for key, value in self.fields.items():  # 属性名 属性描述符对象
            db_column = value.db_column  # 获取属性描述符对象中的属性
            if db_column is None:
                db_column = key.lower()
            fields.append(db_column)
            value = getattr(self, key)  # 获取属性描述符属性的值 __get__方法
            values.append(str(value))
        sql = "insert {db_table}({fields}) value({values})".format(db_table=self._meta["db_table"],
                                                                   fields=",".join(fields), values=",".join(values))
        pass


class User(BaseModel):
    name = CharField(db_column="name", max_length=10)
    age = IntField(min_value=0, max_value=100)

    class Meta:
        db_table = "user"


if __name__ == '__main__':
    user = User(name="b1", age=28)
    # user = User()
    # user.name = "b1"  # 属性描述符set方法赋值
    # user.age = 28
    user.save()